﻿using System;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using ReflectionStudio.Core.Events;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>
    /// 
    public partial class QFTMCO
    {
        DataRow dwActProce = null;
        DataRow dwActExProce = null;
        CollectionViewSource vwPROCSUPP
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwPROCSUPP");
            }
        }
        DataRow dwPROCSUPP
        {
            get
            {
                if (vwPROCSUPP.View == null)
                    return null;
                if ((DataRowView)vwPROCSUPP.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwPROCSUPP.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwPRODCOST
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwPRODCOST");
            }
        }
        DataRow dwPRODCOST
        {
            get
            {
                if (vwPRODCOST.View == null)
                    return null;
                if ((DataRowView)vwPRODCOST.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwPRODCOST.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwVAPRICE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVAPRICE");
            }
        }
        DataRow dwVAPRICE
        {
            get
            {
                if (vwVAPRICE.View == null)
                    return null;
                if ((DataRowView)vwVAPRICE.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVAPRICE.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwVAMAT
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVAMAT");
            }
        }
        DataRow dwVAMAT
        {
            get
            {
                if (vwVAMAT.View == null)
                    return null;
                if ((DataRowView)vwVAMAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVAMAT.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwVAPROC
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVAPROC");
            }
        }
        DataRow dwVAPROC
        {
            get
            {
                if (vwVAPROC.View == null)
                    return null;
                if ((DataRowView)vwVAPROC.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVAPROC.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwEXVAPROC
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwEXVAPROC");
            }
        }
        DataRow dwEXVAPROC
        {
            get
            {
                if (vwEXVAPROC.View == null)
                    return null;
                if ((DataRowView)vwEXVAPROC.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEXVAPROC.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWPPRICE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwWPPRICE");
            }
        }
        DataRow dwWPPRICE
        {
            get
            {
                if (vwWPPRICE.View == null)
                    return null;
                if ((DataRowView)vwWPPRICE.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWPPRICE.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWFPRICE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwWFPRICE");
            }
        }
        DataRow dwWFPRICE
        {
            get
            {
                if (vwWFPRICE.View == null)
                    return null;
                if ((DataRowView)vwWFPRICE.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWFPRICE.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwRYARNPRICE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwRYARNPRICE");
            }
        }
        DataRow dwRYARNPRICE
        {
            get
            {
                if (vwRYARNPRICE.View == null)
                    return null;
                if ((DataRowView)vwRYARNPRICE.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwRYARNPRICE.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwGS03PRICE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwGS03PRICE");
            }
        }
        DataRow dwGS03PRICE
        {
            get
            {
                if (vwGS03PRICE.View == null)
                    return null;
                if ((DataRowView)vwGS03PRICE.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwGS03PRICE.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwActive = null;
        DataRow actrow = null;
        private void btnQuNew_Click(object sender, RoutedEventArgs e)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            try
            {
                SetData.QUPROCESS.Clear();
                SetData.QUTMASTER.Clear();
                //增加一行，并移动到最后一行
                m_Data.SETINTEXDB = SetData;                
                 m_Data.BuidMatBOMCost(null);
                 
                 m_Data.BuidProcessCost( null);
                 m_Data.RefreshCost();
                //Refresh("VAPRICE");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        
        private void dlgMaster_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                //vwActive = view.SourceCollection;
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    DataRow row = drv.Row;
                    actrow = row;
                    //AddCost(row);
                    string task = (string)sd.Tag;
                    if (task != "RYARNPRICE")
                    {
                        task = "VAPRICE";
                    }
                    Refresh(task, row["QUBOMID"].ToString());
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void dlgYarnPrice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                actrow["QUCPRICE"] = dwRYARNPRICE["YCPRICE"];
                actrow["QUSUPNAME"] = dwRYARNPRICE["YSUPNAME"];
                string UOM = dwGS03PRICE["QUUOM"].ToString();
                double qty = System.Convert.ToDouble(actrow["QUFQUANTITY"].ToString());
                double price = System.Convert.ToDouble(actrow["QUCPRICE"].ToString());
                double value = System.Math.Round(qty * price, 3);
                actrow["QUCVALUE"] = value;
                //自己更新，更新总表，更新相关表
                UpdateMaster(actrow);
                //Refresh("WFPRICE");
                //Refresh("WPPRICE"); 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void AddCost(DataRow dwTarget)
        {
            try
            {
                DataTable tbMaster = SetData.QUTMASTER;
                DataTable tbProcess = SetData.QUPROCESS;
                string bomid = dwTarget["QUBOMID"].ToString();
                string cond = "";
                double mat = 0.0, prod = 0.0;
                DataRow[] rows = null;
                cond = "QUSBOMID='" + bomid + "'";
                rows = tbMaster.Select(cond);
                mat = 0.0;
                if (rows.Length == 0)
                {
                    return;
                }
                foreach (DataRow dwTemp in rows)
                {
                    mat += System.Convert.ToDouble(dwTemp["QUCVALUE"].ToString());
                }
                dwTarget["QUMATCOST"] = mat;
                cond = "QPMASTERID='" + bomid + "'";
                rows = tbProcess.Select(cond);
                prod = 0.0;
                foreach (DataRow dwTemp in rows)
                {
                    prod += System.Convert.ToDouble(dwTemp["QPCVALUE"].ToString());
                }
                dwTarget["QUPRODCOST"] = prod;
                double value = mat + prod;
                dwTarget["QUCVALUE"] = value;
                double qty = System.Convert.ToDouble(dwTarget["QUFQUANTITY"].ToString());
                double price = System.Math.Round(value / qty, 2);
                dwTarget["QUCPRICE"] = price;
                dwTarget["QUCVALUE"] = value;
                UpdateMaster(dwTarget);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = (Button)sender;
                string task = btn.Tag as string;
                CollectionViewSource vws = null;
                Refresh(task);
                //刷新界面。
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //AddCost(actrow);
                Button btn = (Button)sender;
                string task = btn.Tag as string;
                CollectionViewSource vws = null;
                switch (task)
                {
                    case "VAPRICE":
                        vws = vwActive;
                        break;
                    case "RYARNPRICE":
                        double ttryarnvalue = 0;
                        foreach (DataRow dwTemp in ((DataTable)vwGS03PRICE.Source).Rows)
                        {
                            ttryarnvalue += System.Convert.ToDouble(dwTemp["QUCVALUE"].ToString());
                        }
                        zoneRYarn.Header = "原纱总价:" + System.Math.Round(ttryarnvalue, 2).ToString();
                        zoneRawYarnSupplier.IsExpanded = false;
                        zoneRYarn.IsExpanded = false;
                        Refresh("VAPRICE");
                        Refresh("WFPRICE");
                        Refresh("WPPRICE");
                        break;
                    default:
                        break;
                }
                DataTable da = null;
                da = (DataTable)((System.Data.DataView)(((System.Windows.Data.BindingListCollectionView)dlgWPYARN.ItemsSource).SourceCollection)).Table;
                if (da != null)
                {
                    foreach (DataRow dwTemp in da.Rows)
                    {
                        AddCost(dwTemp);
                    }
                }
                da = null;
                da = (DataTable)((System.Data.DataView)(((System.Windows.Data.BindingListCollectionView)dlgWFYARN.ItemsSource).SourceCollection)).Table;
                if (da != null)
                {
                    foreach (DataRow dwTemp in da.Rows)
                    {
                        AddCost(dwTemp);
                    }
                }
                da = null;
                da = (DataTable)((System.Data.DataView)(((System.Windows.Data.BindingListCollectionView)dlgVAPRICE.ItemsSource).SourceCollection)).Table;
                if (da != null)
                {
                    foreach (DataRow dwTemp in da.Rows)
                    {
                        AddCost(dwTemp);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void Refresh(string task, string bomid = "")
        {
            DataTable tbMaster = SetData.QUTMASTER;
            DataTable tbProce = SetData.QUPROCESS;
            string cond = "";
            DataRow[] rows = null;
            string sbomid = "";
            DataRow row = null;
            string supplier = "";
            try
            {
                switch (task)
                {
                    case "VAPRICE":
                        if (bomid == "")
                        {
                            vwVAPRICE.Source = null;
                            #region======VA========
                            cond = "QUSTAGE>'3'";
                            rows = tbMaster.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    vwVAPRICE.Source = rows.CopyToDataTable();
                                    //vwVAPRICE.View.MoveCurrentToFirst();
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            //dlgMATSupplier.ItemsSource=null;
                            //dlgVAPROC.ItemsSource=null;
                            //dlgEXVAPROC.ItemsSource = null;
                            /*dlgMATSupplier.Items.Clear();
                            dlgVAPROC.Items.Clear();
                            dlgEXVAPROC.Items.Clear();*/
                            vwVAMAT.Source = null;
                            vwVAPROC.Source = null;
                            cond = "QPMASTERID='" + bomid + "'";
                            rows = tbProce.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    this.vwVAPROC.Source = rows.CopyToDataTable();
                                    //vwVAPROC.View.MoveCurrentToFirst();
                                }
                            }
                        }
                        break;
                    case "WPPRICE":
                        #region==============WarpYarn================
                        if (bomid == "")
                        {
                            vwWPPRICE.Source = null;
                            vwVAMAT.Source = null;
                            vwVAPROC.Source = null;
                            cond = "QUSTAGE='22' and QUJW='J'";
                            rows = tbMaster.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    vwWPPRICE.Source = rows.CopyToDataTable();
                                    //vwWPPRICE.View.MoveCurrentToFirst();
                                    zoneWPYarn.IsExpanded = true;
                                }
                            }
                        }
                        #endregion
                        break;
                    case "WFPRICE":
                        #region==============Weft Yarn================
                        if (bomid == "")
                        {
                            vwWFPRICE.Source = null;
                            vwVAMAT.Source = null;
                            vwVAPROC.Source = null;
                            cond = "QUSTAGE='21' and QUJW='W'";
                            rows = tbMaster.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    vwWFPRICE.Source = rows.CopyToDataTable();
                                    //vwWFPRICE.View.MoveCurrentToFirst();
                                    zoneWFYarn.IsExpanded = true;
                                }
                            }
                        }
                        if (bomid != "")
                        {
                            vwVAMAT.Source = null;
                            vwVAPROC.Source = null;
                            cond = "QUSBOMID='" + bomid + "'";
                            rows = tbMaster.Select(cond);
                            if (rows.Length == 0)
                                return;
                            vwVAMAT.Source = rows.CopyToDataTable();
                            cond = "QPMASTERID='" + bomid + "'";
                            rows = tbProce.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    this.vwVAPROC.Source = rows.CopyToDataTable();
                                }
                            }
                        }
                        #endregion
                        break;
                    case "RYARNPRICE":
                        #region======GS03========
                        if (bomid == "")
                        {
                            vwGS03PRICE.Source = null;
                            cond = "QUSOURCETYPE='P'";
                            rows = tbMaster.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    vwGS03PRICE.Source = rows.CopyToDataTable();
                                    //vwGS03PRICE.View.MoveCurrentToFirst();
                                }
                                zoneRYarn.IsExpanded = true;
                            }
                        }
                        if (bomid != "")
                        {
                            supplier = actrow["QUSUPNAME"].ToString().Trim();
                            string art = actrow["QUARTICLE"].ToString();
                            string var = actrow["QUVAR"].ToString();
                            string color = actrow["QUCOLOR"].ToString();
                            cond = "YYARN='" + art + "' and YVAR='" + var + "' and YCOLOR='" + color + "'";
                            rows = SetData.YARNPRICE.Select(cond);
                            if (rows != null)
                            {
                                if (rows.Length > 0)
                                {
                                    vwRYARNPRICE.Source = rows.CopyToDataTable();
                                    zoneRawYarnSupplier.IsExpanded = true;
                                    #region==Locate Supplier==
                                    if (vwRYARNPRICE.View == null)
                                        return;
                                    vwRYARNPRICE.View.MoveCurrentToFirst();
                                    //vwRYARNPRICE.View.MoveCurrentToFirst();
                                    if (supplier != "")
                                    {
                                        while (!vwRYARNPRICE.View.IsCurrentAfterLast)
                                        {
                                            row = null;
                                            if (vwRYARNPRICE.View.CurrentItem != null)
                                            {
                                                row = ((DataRowView)vwRYARNPRICE.View.CurrentItem).Row;
                                            }
                                            if (row != null)
                                            {
                                                if (row["YSUPNAME"].ToString().Trim() == supplier)
                                                    break;
                                            }
                                            vwRYARNPRICE.View.MoveCurrentToNext();
                                        }
                                    }
                                    #endregion
                                }
                            }

                        }
                        #endregion
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void RefreshProcessflow(string task, string proc, string supplier = "")
        {
            DataTable tbProce = SetData.QUPROCESS;
            string cond = "";
            DataRow[] rows = null;
            string sbomid = "";
            DataRow row = null;
            try
            {
                cond = "QPROCESS='" + proc + "'";
                rows = SetData.PRODCOST.Select(cond);
                vwEXVAPROC.Source = null;
                if (rows == null)
                    return;
                if (rows.Length == 0)
                    return;
                vwEXVAPROC.Source = rows.CopyToDataTable();
                #region===Locate Supplier======
                if (vwEXVAPROC.View == null)
                    return;
                vwEXVAPROC.View.MoveCurrentToFirst();
                if (supplier != "")
                {
                    while (!vwEXVAPROC.View.IsCurrentAfterLast)
                    {
                        row = null;
                        if (vwEXVAPROC.View.CurrentItem != null)
                        {
                            row = ((DataRowView)vwEXVAPROC.View.CurrentItem).Row;
                        }
                        if (row != null)
                        {
                            if (row["QSUPNAME"].ToString().Trim() == supplier)
                                break;
                        }
                        vwEXVAPROC.View.MoveCurrentToNext();
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void UpdateMaster(DataRow dwSource)
        {
            try
            {
                var query = from dwTemp in SetData.QUTMASTER.AsEnumerable()
                            where dwTemp["QUBOMID"].ToString() == dwSource["QUBOMID"].ToString()
                            & dwTemp["QUSBOMID"].ToString() == dwSource["QUSBOMID"].ToString()
                            select dwTemp;
                foreach (DataRow dwTemp in query)
                {
                    dwTemp["QUCPRICE"] = dwSource["QUCPRICE"];
                    dwTemp["QUFPRICE"] = dwSource["QUFPRICE"];
                    dwTemp["QUPPRICE"] = dwSource["QUPPRICE"];
                    dwTemp["QUSUPNAME"] = dwSource["QUSUPNAME"];
                    dwTemp["QUCVALUE"] = dwSource["QUCVALUE"];
                    dwTemp["QUFVALUE"] = dwSource["QUFVALUE"];
                    dwTemp["QUPVALUE"] = dwSource["QUPVALUE"];
                    dwTemp["QUPRODCOST"] = dwSource["QUPRODCOST"];
                    dwTemp["QUMATCOST"] = dwSource["QUMATCOST"];
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #region========ProcessFlow===============
        private void dlgPROC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    if (drv == null)
                        return;
                    DataRow row = drv.Row;
                    dwActProce = row;
                    string proc = (string)sd.Tag;
                    RefreshProcessflow(proc, dwActProce["QPPROCESS"].ToString(), dwActProce["QPSUPPLIER"].ToString().Trim());
                }
                //触发选择供应商
                //供应商确定之后，根据MasterID和
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void ResetProcessCost(string task, DataRow dwSource)
        {
            try
            {
                if (dwActProce == null)
                    return;
                if (dwSource == null)
                    return;
                dwActProce["QPCPRICE"] = dwSource["QCPRICE"];
                dwActProce["QPUOM"] = dwSource["QUOM"];
                dwActProce["QPSUPPLIER"] = dwSource["QSUPNAME"];
                dwActProce["QPPROCDES"] = dwSource["QFDESCRIPTION"];
                UpdateValue(dwActProce);
                string masterid = dwActProce["QPMASTERID"].ToString();
                string proc = dwActProce["QPPROCESS"].ToString();
                var query = from dwTemp in SetData.QUPROCESS.AsEnumerable()
                            where dwTemp["QPMASTERID"].ToString() == masterid
                            & dwTemp["QPPROCESS"].ToString() == proc
                            select dwTemp;
                foreach (DataRow dwTemp in query)
                {
                    dwTemp["QPCPRICE"] = dwActProce["QPCPRICE"];
                    dwTemp["QPUOM"] = dwActProce["QPUOM"];
                    dwTemp["QPSUPPLIER"] = dwActProce["QPSUPPLIER"];
                    dwTemp["QPCVALUE"] = dwActProce["QPCVALUE"];
                    dwTemp["QPPROCDES"] = dwActProce["QPPROCDES"];

                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void UpdateValue(DataRow dwProce)
        {
            try
            {
                string UOM = dwProce["QPUOM"].ToString();
                double qty = System.Convert.ToDouble(dwProce["QPQUANTITY"].ToString());
                double price = System.Convert.ToDouble(dwProce["QPCPRICE"].ToString());
                double value = qty * price;
                if (UOM == "W")
                {
                    double qty1 = System.Convert.ToDouble(dwProce["QPQTY1"].ToString());
                    value = qty1 * price;
                }
                if (UOM == "YD")
                {
                    double qtyd = qty/0.9144;
                    value = qtyd * price;
                }
                dwProce["QPCVALUE"] = System.Math.Round(value, 3);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void dlgEXPROC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    if (drv == null)
                        return;
                    DataRow row = drv.Row;
                    string task = (string)sd.Tag;
                    ResetProcessCost(task, row);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #endregion
    }
}
